<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>商品搜索系统</title>
    <style>
        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }

        .search-box {
            margin-bottom: 20px;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 8px;
        }

        .form-inline {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
        }

        .form-inline label {
            font-size: 14px;
            margin-right: 8px;
        }

        .form-inline input {
            font-size: 14px;
            padding: 6px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        button {
            font-size: 14px;
            padding: 6px 15px;
            cursor: pointer;
        }

        .product-item {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 10px;
        }

        .colour-item {
            margin-left: 30px;
            padding: 10px;
            border-left: 3px solid #007bff;
            margin-top: 8px;
        }

        .hidden {
            display: none;
        }
    </style>
</head>
<body>
<div class="container">

    <div style="margin-bottom: 20px;">
        <a href="index.html" style="font-size: 16px; text-decoration: none; color: #007bff;">返回到商品列表</a>
    </div>

    <div class="search-box">
        <h2 style="font-size: 18px; margin-bottom: 15px;">商品搜索</h2>

        <!--
                <div class="form-inline search-panel">
                    <div class="form-group">
                        <label for="productNo">货号：</label>
                        <input type="text" id="productNo" placeholder="请输入货号" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="colour">颜色：</label>
                        <input type="text" id="colour" placeholder="请输入颜色" class="form-control">
                    </div>
                    <button onclick="searchProducts()" class="btn btn-success">搜索</button>
                </div>
        -->

        <button id="taskStatusBtn" class="btn btn-primary" onclick="toggleTaskStatus()">加载中...</button>
    </div>

    <div id="results"></div>
</div>

<script>


    var socket = null;
    var heartbeatInterval = null;
    var reconnectAttempts = 0;
    var maxReconnectAttempts = 5;
//8.152.154.163
    function connectWebSocket() {
        if ('WebSocket' in window) {
           socket = new WebSocket("ws://8.152.154.163:8090/websocket/server");
         //   socket = new WebSocket("ws://localhost:8090/websocket/server");
        } else if ('MozWebSocket' in window) {
           socket = new MozWebSocket("ws://8.152.154.163:8090/websocket/server");
          //  socket = new MozWebSocket("ws://localhost:8090/websocket/server");
        } else {
           socket = new SockJS("http://8.152.154.163:8090/sockjs/server");
           // socket = new SockJS("http://localhost:8090/sockjs/server");
        }

        // 接收消息触发
        socket.onmessage = function (event) {
            console.log('Received message: ' + event.data);
           // socket.send(JSON.stringify({type: 'heartbeat'}));
            // 清除之前的heartbeat定时器
            //  clearInterval(heartbeatInterval);
            // 重新启动heartbeat定时器
            //   startHeartbeat();
            // 处理接收到的消息
            renderResults(event.data)
        };
        // 创建连接触发
        socket.onopen = function (event) {
            console.log(event.type);
        };
        // 连接异常触发
        socket.onerror = function (event) {
            console.log(event)
        };
        // 关闭连接触发
        socket.onclose = function (closeEvent) {
            console.log(closeEvent.reason);
        };

        // 启动心跳定时器
        startHeartbeat();
    }

    function startHeartbeat() {
        // 每30秒发送一次心跳
        heartbeatInterval = setInterval(function () {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.send(JSON.stringify({type: 'heartbeat'}));
            }
        }, 3000);

        // 设置超时检测
        setTimeout(function () {
            if (socket && socket.readyState !== WebSocket.OPEN) {
                handleConnectionError();
            }
        }, 45000);
    }

    function handleConnectionError() {
        clearInterval(heartbeatInterval);
        if (reconnectAttempts < maxReconnectAttempts) {
            reconnectAttempts++;
            setTimeout(function () {
                console.log('尝试重新连接... 第' + reconnectAttempts + '次');
                connectWebSocket();
            }, 5000 * reconnectAttempts); // 指数退避重试
        } else {
            console.error('无法重新连接到服务器，请检查网络状况');
        }
    }

    // 初始化连接
    connectWebSocket();


    function getTaskStatus() {
        fetch('/arcteryx/switch/status', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({})
        })
            .then(response => response.json())
            .then(data => {
                const btn = document.getElementById('taskStatusBtn');
                if (data.data.configSwitch === 1) {
                    btn.textContent = '结束任务';
                    btn.className = 'btn btn-success';
                } else {
                    btn.textContent = '开始任务';
                    btn.className = 'btn btn-danger';
                }
            })
            .catch(error => {
                console.error('Error fetching task status:', error);
                document.getElementById('taskStatusBtn').textContent = '获取状态失败';
            });
    }

    function toggleTaskStatus() {
        const btn = document.getElementById('taskStatusBtn');
        const newStatus = btn.textContent === '开始任务';

        fetch('/arcteryx/switch/change', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({configSwitch: newStatus})
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    getTaskStatus(); // Refresh status
                } else {
                    alert(`操作失败: ${data.message}`);
                }
            })
            .catch(error => {
                console.error('Error toggling task status:', error);
                alert('操作请求异常');
            });
    }

    // 页面加载完成后立即获取一次任务状态
    document.addEventListener('DOMContentLoaded', getTaskStatus);

    function searchProducts() {
        const productNos = document.getElementById('productNo').value;
        const colour = document.getElementById('colour').value;
        //  fetch('/api/products/search?productNo=' + productNo + '&colour=' + colour)
        fetch('/arcteryx/task/list', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                productNos: productNos,
                colour: colour
            })
        })
            .then(response => response.json())
            .then(data => {
                console.log(' fetching data:', data);
                if (data.success !== true) {
                    // 显示错误信息
                    document.getElementById('results').innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
                    return;
                }
                // 正常处理数据
                renderResults(data.data);
            })
            .catch(error => console.error('Error:', error));
    }

    function renderResults(commodities) {
        const resultsDiv = document.getElementById('results');
        resultsDiv.innerHTML = '';

         // 新增字符串数组处理逻辑
        if (typeof commodities === 'string') {
            try {
                commodities = JSON.parse(commodities);
            } catch (e) {
                console.error('商品数据解析失败:', e);
                resultsDiv.innerHTML = '<div class="alert alert-danger">数据格式错误 - ' + new Date().toLocaleString() + '</div>';
                return;
            }
        }
        // 空数据校验
        if (!commodities || !Array.isArray(commodities) || commodities.length === 0) {
            console.warn('接收到空的商品数据:', commodities);
            resultsDiv.innerHTML = '<div class="alert alert-info">暂无商品信息 - ' + new Date().toLocaleString() + '</div>';
            return;
        }

        commodities.forEach(commodity => {
            // 创建产品容器
            const productContainer = document.createElement('div');
            productContainer.className = 'product-container';
            productContainer.style.border = '1px solid #ddd';
            productContainer.style.padding = '15px';
            productContainer.style.marginBottom = '20px';

            // 产品编号标题
            const productHeader = document.createElement('h3');
            productHeader.textContent = `产品编号: ${commodity.productNo} - 产品型号: ${commodity.productName || '未命名'}`;
            productHeader.style.color = '#333';
            productHeader.style.marginBottom = '15px';

            productContainer.appendChild(productHeader);

            // 遍历链接列表
            commodity.arcteryxLinkVos.forEach(link => {
                const linkItem = document.createElement('div');
                linkItem.className = 'link-item';
                linkItem.style.borderBottom = '1px dashed #eee';
                linkItem.style.padding = '10px 0';

                // 构建HTML结构
                linkItem.innerHTML = `
                <div style="display: flex; align-items: center; margin-bottom: 8px;">
                    <span style="margin-right: 20px;">${link.dateTime || '无时间信息'}</span>

                    <strong style="font-size: 14px; margin-right: 12px;">链接：</strong>
                    <a href="${link.existLink}" target="_blank" style="color: #007bff; text-decoration: underline;">
                        ${link.existLink}
                    </a>

                    ${link.arcteryxColourVoList && link.arcteryxColourVoList.length > 0 ?
                    `<button class="toggle-btn" onclick="toggleDetails(this)"
                            style="margin-left: auto; padding: 3px 8px; background: #f8f9fa; border: 1px solid #ddd;">
                            隐藏详情
                        </button>` :
                    `<span style="color: red; margin-left: auto;">${link.reason || '无库存信息'}</span>`
                }
                </div>

                ${link.arcteryxColourVoList && link.arcteryxColourVoList.length > 0 ? `
                <div class="colour-details" style="display: block; padding-left: 20px; margin-top: 10px;">
                    ${link.arcteryxColourVoList.map(colour => `
                        <div class="colour-item" style="margin-bottom: 8px;">
                            <div><strong>颜色：</strong>${colour.colourLabel}</div>
                            <div><strong>现价：</strong>${colour.realPrice}</div>
                            <div><strong>库存：</strong>${colour.colourInventory}</div>
                        </div>
                    `).join('')}
                </div>` : ''}
            `;

                productContainer.appendChild(linkItem);
            });

            resultsDiv.appendChild(productContainer);
        });
    }

    // 详情展开/收起功能
    function toggleDetails(button) {
        const detailsDiv = button.closest('.link-item').querySelector('.colour-details');
        const isVisible = detailsDiv.style.display !== 'none';
        detailsDiv.style.display = isVisible ? 'none' : 'block';
        button.textContent = isVisible ? '显示详情' : '隐藏详情';
    }
</script>
</body>
</html>
